package org.psyduck.admin.menu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.psyduck.admin.menu.entity.Menu;
import org.psyduck.admin.menu.entity.Route;
import org.psyduck.admin.menu.service.MenuService;
import org.psyduck.common.entity.DataMap;
import org.psyduck.common.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("menu")
public class MenuController {

    @Autowired
    MenuService menuService;

    @RequestMapping("getCurrentUserMenu")
    public List<Route> getCurrentUserMenu(){
        return menuService.getCurrentUserMenu(WebUtils.getUserId());
    }

    @RequestMapping("getMenuTree")
    public List<Menu> getMenuTree() {
        return menuService.getMenuTree();
    }

    @RequestMapping("getMenusByRoleId")
    public List<DataMap> getMenusByRoleId(String roleId){
        return menuService.getDao().getMenusByRoleId(roleId);
    }

    @RequestMapping("save")
    @CacheEvict(value = "userAuth", allEntries=true)
    public String save(@RequestBody Menu menu) {
        menuService.saveOrUpdate(menu);
        return menu.getId();
    }

    @CacheEvict(value = "userAuth", allEntries=true)
    @PreAuthorize("hasAuthority('menu:delete')")
    @RequestMapping("delete")
    public Boolean delete(String id) {
        menuService.recursiveRemoveById(id);
        return true;
    }

    @RequestMapping("getMenuConfig")
    public Menu getMenuConfig(String id){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("list_config","form_config");
        queryWrapper.eq("id",id);
        return menuService.getDao().selectOne(queryWrapper);
    }

    @RequestMapping("changeIsShow")
    public boolean changeIsShow(Menu menu){
        return menuService.updateById(menu);
    }

    @RequestMapping("getSort")
    public Integer getSort(String pid) {
        Integer sort = menuService.getDao().getSort(pid);
        if(null == sort){
            return 10;
        }
        return sort;
    }

}
